#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:set sts=4:tabstop=4:expandtab:shiftwidth=4:
# EasyUbuntu - Install commonly requested apps on your (k/X)ubuntu box 
# Copyright (C) 2006 EasyUbuntu team
# https://launchpad.net/products/easyubuntu
# http://easyubuntu.freecontrib.org
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA
# 
# About this file 
# Show a shell command's output in a gtk.TextView without freezing the UI

from backend import *

import os
import threading
import locale
import gtk
import pygtk
#pygtk.require('2.0')
import subprocess

encoding = locale.getpreferredencoding()
utf8conv = lambda x : unicode(x, encoding).encode('utf8')

class PackageManager:
    
    def __init__(self, packageslist, confdir):
        """ Call Synaptic with different configuration options """
        self.packageslist = packageslist
        self.manager = ["/usr/sbin/synaptic", "--hide-main-window", "--non-interactive"] 
        self.manager.append("-o=dir::etc="+confdir)
        self.manager.append("-o=dir::etc::sourcelist=sources.list")
        print self.manager
    
    def update(self):
        """ Get the last packages list from repositories
        """
        self.manager.append("--update-at-startup")
        print "In update", self.manager
        process = os.popen(" ".join(self.manager), "w")
        process.close() # Run it
    
    def install(self, Packages = None):
        """ Install packages
        """
        self.manager.remove("--update-at-startup")
        self.manager.append("--set-selections")
        print "In Install", self.manager
        process = os.popen(" ".join(self.manager), "w")
        for s in Packages:
            process.write("%s                 install\n" % str(s))
        process.close()

class gtkLogger:

    def __init__(self, packageslist, configslist, confdir):
        self.commandslist = []
        synaptic =PackageManager(packageslist, confdir)
        synaptic.update()
        synaptic.install(Packages = packageslist)

        self.commandslist = processConfig(configslist, confdir)
        if self.commandslist:
            win = gtk.Window()
            win.resize(500,500)
            win.connect('delete-event', gtk.main_quit)
            sw = gtk.ScrolledWindow()
            sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
            self.textview = gtk.TextView()
            self.textbuffer = self.textview.get_buffer()
            sw.add(self.textview)
            button = gtk.Button('Close',stock=gtk.STOCK_CLOSE)
            button.connect("clicked", gtk.main_quit )
            vbox = gtk.VBox()
            vbox.pack_start(sw)
            vbox.pack_start(button, False, False)
            win.add(vbox)
            win.show_all()
            #gtk.main()
            
            #self.pkgcommandslist = processInstall(packageslist,  confdir)
            
            #for cmds in self.pkgcommandslist:
            #    self.commandslist.append(cmds)
            self.runCommand()

    def runCommand(self):
        for command in self.commandslist:
            thr = threading.Thread(target= self.read_output, args=(buffer, command))
            thr.run()

    def read_output(self, buffer, command):
        stdin, stdouterr = os.popen4(command)
        for line in stdouterr.readlines():
            self.textbuffer.insert(self.textbuffer.get_end_iter(), utf8conv(line))
